<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="topicForm" :rules="rules" ref="topicRef" label-width="100px" class="topicForm">
        <el-button @click="addOption">添加选项</el-button>
        <el-form-item label="题目名称" prop="topicname">
          <el-input style="width: 300px" v-model="topicForm.topicname" placeholder="请输入题目名称"></el-input>
        </el-form-item>
        <el-form-item label="" prop="topicname" v-if="topicForm.topicoption.length">
            <div style="display:flex;width: 100%;">
                <div  style="width:150px;text-align: center;">
                    选项内容
                </div>
                <div style="width:90px;text-align: center;">
                    选项分数
                </div>
            </div>
        </el-form-item>
        <el-form-item
            v-for="(option, index) in topicForm.topicoption"
            :key="index"
            :label="'选项' + (index-0+1)"
            :prop="'topicoption[' + index + ']'"
            >
            <div style="display:flex">
                <div  style="width:150px;text-align: center;">
                    <el-input v-model="option.context" />
                </div>
                <div style="width: 90px;text-align: center;">
                    <el-input v-model="option.score" />
                </div>  
                <el-button @click.prevent="removeOption(option)">删除选项</el-button>
            </div>
           
            <!-- <el-button class="mt-2" @click.prevent="removeDomain(domain)">
                Delete
            </el-button> -->
        </el-form-item>
        <el-form-item label="排序值" prop="order">
          <el-input type="number" max='200' v-model="topicForm.order"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from '@/utils'
export default {
  name: 'Addtopic',
  setup() {
    const { proxy } = getCurrentInstance()
    console.log('proxy', proxy)
    const topicRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    let { id,appraisal_id } = route.query
    const state = reactive({
      uploadImgServer,
      token: localGet('token') || '',
      id: id,
      topicForm: {
        topicname: '',
        topicoption:[],
        order:'',
        appraisal_id:appraisal_id,
      },
      rules: {
        topicurl: [
          { required: 'true', message: '请上传视频', trigger: ['change'] }
        ],
        topicname: [
          { required: 'true', message: '请填写视频名称', trigger: ['change'] }
        ],
        order: [
          { required: 'true', message: '请填写排序值', trigger: ['change'] }
        ],
      },
    })
    onMounted(() => {
      if (id) {
        axios.get(`/topic/${id}`).then(res => {
          console.log(res);
          // const { topic, firstCategory, secondCategory, thirdCategory } = res
          // console.log('topic',topic)
          const topic = res;
          state.topicForm = {
            topicname: topic.topicname,
            topicoption: JSON.parse(topic.topicoption),
            order: topic.order,
            appraisal_id:topic.appraisal_id
          }
        })
      }
    })
    const submitAdd = () => {
      topicRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          let httpOption = axios.post
          let params = {
            topicname: state.topicForm.topicname,
            topicoption: JSON.stringify(state.topicForm.topicoption),
            order: state.topicForm.order,
            appraisal_id:state.topicForm.appraisal_id
          }
          if (params.topicname.length > 128) {
            ElMessage.error('题目名称不能超过128个字符')
            return
          }
          console.log('params', params)
          if (id) {
            params.id = id
            // 修改课程使用 put 方法
            httpOption = axios.put
          }
          httpOption('/topic', params).then(() => {
            ElMessage.success(id ? '修改成功' : '添加成功')
            let queryId = id ? state.topicForm.appraisal_id : appraisal_id
            router.push({ path: '/appraisal_topic',query:{ id :queryId}} )
            // router.push({ path: '/add', query: { id } })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png','ogg'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleUrlSuccess = (val) => {
      state.topicForm.topicurl = val.data || ''
    }
    const addOption = () => {
        state.topicForm.topicoption.push({
            context:'',
            score : 0
        })
    }
    const removeOption = (item) => {
        const index = state.topicForm.topicoption.indexOf(item)
        if (index !== -1) {
            state.topicForm.topicoption.splice(index, 1)
        }
    }
    return {
      ...toRefs(state),
      topicRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
      addOption,
      removeOption
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>